package com.hh.common;

import com.hh.entity.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public class DaoImp<T> implements dao<T> {
    @Autowired
    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    public SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }

    @Override
    public void updata(T eneity) {
       getSessionFactory().getCurrentSession().save(eneity);

    }

    @Override
    public Person getByid(Integer id) {
        String hql="from Person where id= :id";
        Query query=getSessionFactory().getCurrentSession().createQuery(hql);
        query.setParameter("id",id);
        List list= query.list();
        for (Object p:list){
            System.out.println(p);
        }
        return (Person) list.get(0);
    }

    @Override
    public List<T> findAll(Class<T> c) {
        System.out.println("——————————————");
        String nameClass= c.getSimpleName();
        System.out.println(nameClass);
         StringBuilder stringBuilder=new StringBuilder("From ");
        stringBuilder.append(nameClass);
        return getSessionFactory().getCurrentSession().createQuery(stringBuilder.toString()).list();
    }
}
